from rest_framework import serializers
from django_redis import get_redis_connection
import logging
logger = logging.getLogger('django')
class ImageCodeCheckSerializer(serializers.Serializer):

    image_code_id = serializers.UUIDField()
    text = serializers.CharField(max_length=4, min_length=4)

    def validate(self, attrs):
        image_code_id = attrs['image_code_id']
        text = attrs['text']
        redis_conn = get_redis_connection('verify_codes')

        real_text = redis_conn.get('img_%s' % image_code_id)

        if real_text is None:
            raise serializers.ValidationError('验证码已过期')

        try:
            redis_conn.delete('img_%s' % image_code_id)
        except Exception as e:
            logger.error(e)


        if real_text.decode().lower() != text.lower():
            raise serializers.ValidationError('验证码输入错误')
        mobile = self.context['view'].kwargs['mobile']
        real_flag = redis_conn.get('sms_flag%s' % mobile)
        if real_flag:
            raise serializers.ValidationError('请求太过频繁')
        return attrs

























